package dbms.ypr;

import dbms.ypr.user.DataBasePermissions;
import dbms.ypr.user.User;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


public class Use {

    public static void useSql(String sql){
        String dbName = sql.substring(4, sql.length()-1);
        //System.out.println(dbName);
        String path = SQLConstant.getPath();

        List<String> dbList = dbms.ypr.Utils.getAllDatabase(path);

        boolean b = dbList.contains(dbName);
        User loginUser = User.getLoginUser(SQLConstant.currentUsername);
        List<String> collect = null;
        if (loginUser.getDataBasePermissions() != null){
            collect = loginUser.getDataBasePermissions().stream().map(DataBasePermissions::getDatabaseName).collect(Collectors.toList());
        } else {
            collect = new ArrayList<>();
        }
        if(b && collect.contains(dbName)){
            SQLConstant.setNowPath(SQLConstant.getNowPath() + "\\" + dbName);
            SQLConstant.currentDatabase = dbName;
            System.out.println("Database changed");
            Input.get();
        }
        else{
            System.out.println("ERROR: 数据库不存在");
            Input.get();
        }
    }
}
